package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.constant.ClueTrackRecordType;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.clue.ClueDO;
import com.qk.domain.clue.CluePoolDO;
import com.qk.dto.clue.*;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.ClueTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.vo.ClueVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Service
@SuppressWarnings("all")
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {
    @Autowired
    private  UserMapper userMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    @Autowired
    private BusinessMapper businessMapper;

    @Override
    public PageResult<CluePoolDO> selectCluePoolPage(CluePoolDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<CluePoolDO> list = this.baseMapper.selectCluePoolPage(dto);
        Page<CluePoolDO> page =(Page<CluePoolDO>)list ;
        return  PageResult.<CluePoolDO>builder()
                .total(page.getTotal())
                .rows(page.getResult())
                .build();
    }

    @Transactional
    @Override
    public void markFalseClue(Integer id, MarkFalseClueDto dto) {
        //查询线索信息
        Clue clue = this.baseMapper.selectById(id);
        //更新线索状态
        clue.setStatus(ClueStatusConstants.PSEUDO_CLUE);
        this.baseMapper.updateById(clue);
        //添加跟进记录
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        clueTrackRecord.setType(ClueTrackRecordType.PSEUDO_CLUE);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        this.clueTrackRecordMapper.insert(clueTrackRecord);

    }

    @Transactional
    @Override
    public void convertToBusiness(Integer id) {

        Clue clue = this.baseMapper.selectById(id);
        clue.setStatus(ClueStatusConstants.TRANSFORM_TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);

        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setNextTime(null);
        business.setUserId(null);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        this.businessMapper.insert(business);

    }

    /**
     *@Transactional：事务注解
     * @param
     */
    @Transactional
    @Override
    public void updateClueInfoById(UpdateClueInfoDTO dto) {
        //1.将数据修改到Clue表中
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        //1.2补全数据
        clue.setUpdateTime(LocalDateTime.now());
        if (clue.getStatus()==ClueStatusConstants.WAIT_ALLOCATION){
            clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        }
        //1.3保存数据到Clue表中
        this.baseMapper.updateById(clue);

        //2.将数据添加到ClueTrackRecord表中
        //copy json数据到ClueTrackRecord
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(dto, ClueTrackRecord.class);
        //2.2补全数据
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        //todo 设置跟进用户id还在在拦截器中，还没有获取
        //自己指定UserId 数据
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL_FOLLOW_UP);
        //2.3保存数据到ClueTrackRecord表中
        this.clueTrackRecordMapper.insert(clueTrackRecord);
    }

    @Override
    public ClueVO getClueInfoById(Integer id) {
        //获取线索信息
        Clue clue = this.baseMapper.selectById(id);
        //获取线索的负责人信息
        Integer userId = clue.getUserId();
        User user = userMapper.getUserById(userId);
        //根据线索id获取跟进记录
        List<ClueTrackRecord> clueTrackRecords = clueTrackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class)
                .in(ClueTrackRecord::getClueId, id));
        //数据组装：封装VO
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueVO.ClueTrackRecordVO> list = clueTrackRecords.stream().map(item -> {
            ClueVO.ClueTrackRecordVO vo = BeanUtil.copyProperties(item, ClueVO.ClueTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        //将集合赋给VO里的trackRecords属性
        clueVO.setTrackRecords(list);

        return clueVO;
    }
    @Override
    public PageResult<ClueDO> selectPage(ClueQueryDto dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<ClueDO> list = this.baseMapper.selectByPage(dto);
        Page<ClueDO> page =(Page<ClueDO>)list ;
        return PageResult.<ClueDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows( page.getResult())
                .build();
    }

    @Override
    public void addClue(ClueDTO dto) {
        if(ObjectUtil.isEmpty(dto.getPhone())||ObjectUtil.isEmpty(dto.getChannel())){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        //将DTO转成实体（Clue） bean拷贝
        Clue clue = BeanUtil.copyProperties(dto, Clue.class);
        //设置创建时间和修改时间 (表中不为空)
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        //设置线索状态，默认为待分配 使用静态常量；
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        //保存数据到Clue表中
        //方法一：使用ClueMapper中的insert方法
        //this.baseMapper.insert(clue);

        //方法二：使用ServiceImpl中的save方法
        this.save(clue);
    }

}
